package com.github.llyb120.calengine.rule;

import com.github.llyb120.performance.define.Dataset;
import com.github.llyb120.performance.define.Datasource;
import lombok.Synchronized;
import org.beetl.sql.core.*;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DatasourceWrapper extends Datasource{
    private RuleEngine ruleEngine;
    private Datasource innerObject;
    private static Map<String, SQLManager> sqlManagers = new ConcurrentHashMap<>();

    public DatasourceWrapper(RuleEngine ruleEngine, Datasource dataset) {
        this.ruleEngine = ruleEngine;
        this.innerObject = dataset;
    }

//    public static SQLManager getSqlManager(String dsName){
//        return ruleEngine.getDatasource(dsName).getSqlManager();
//    }
    public SQLManager getSqlManager() {
        synchronized (sqlManagers){
            SQLManager sqlManager = sqlManagers.get(getName());
            if (sqlManager == null) {
                ConnectionSource source = ConnectionSourceHelper.getSimple(getDriver(), getUrl(), getUsername(), getPassword());
//source是唯一必须的参数，其他参数都有默认值
                SQLManagerBuilder builder = new SQLManagerBuilder(source);
//设置NameConversion，这里数据库命名采用下划线风格，使用UnderlinedNameConversion
                builder.setNc(new DefaultNameConversion());
//设置一个拦截器，输出debug日志，包含了sql语句和执行参数，执行时间
                builder.setInters(new Interceptor[]{new DebugInterceptor()});
//设置数据库分隔，必须跟数据库一样
                builder.setDbStyle(new MySqlStyle());
                sqlManager = builder.build();
                sqlManagers.put(getName(), sqlManager);
            }
            return sqlManager;
        }

    }




    @Override
    public String getName() {
        return innerObject.getName();
    }

    @Override
    public void setName(String name) {
        innerObject.setName(name);
    }

    @Override
    public String getUrl() {
        return innerObject.getUrl();
    }

    @Override
    public void setUrl(String url) {
        innerObject.setUrl(url);
    }

    @Override
    public String getDriver() {
        return innerObject.getDriver();
    }

    @Override
    public void setDriver(String driver) {
        innerObject.setDriver(driver);
    }

    @Override
    public String getUsername() {
        return innerObject.getUsername();
    }

    @Override
    public void setUsername(String username) {
        innerObject.setUsername(username);
    }

    @Override
    public String getPassword() {
        return innerObject.getPassword();
    }

    @Override
    public void setPassword(String password) {
        innerObject.setPassword(password);
    }
}
